package com.lindenvalley.ch;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;

import com.lindenvalley.ch.adapters.SearchWeekTaskAdapter;
import com.lindenvalley.ch.application.BerichtApplication;
import com.lindenvalley.ch.content.Task;
import com.lindenvalley.ch.content.User;
import com.lindenvalley.ch.content.Week;
import com.lindenvalley.ch.content.Weeks;
import com.lindenvalley.ch.network.OfflineTaskFactory;
import com.lindenvalley.ch.network.OnlineTaskFactory;
import com.lindenvalley.ch.network.TaskInterface;
import com.lindenvalley.ch.network.WorkServer;

public abstract class AbstractHomeActivity extends Activity {

	protected final String TAG = getClass().getSimpleName();
	protected static final int ADD_DIALOG_ID = 1000;
	protected static final int SEARCH_DIALOG_ID = 1001;
	protected static final int CHOICE_FIRST_WEEK_DIALOG_ID = 1004;
	protected static final int PDF_DIALOG_ID = 1005;
	protected static final String weekString = "KW ";
	private static final int ADD_RESULT_OK = 2;
	private static final int SHARE_RESULT_OK = 3;
	private static final int SEARCH_RESULT_OK = 4;
	public static final int NO_WEEK_INDEX = -1;
	protected int maxCharsToLabel;
	protected Calendar calendar;
	protected final static String dateFormatPattern = "dd.MM.yyyy";
	protected SimpleDateFormat dateFormat;
	protected User user;
	protected WorkServer server;
	protected Weeks weeks;
	protected int currentWeekIndex = NO_WEEK_INDEX;
	protected Week currentWeek;
	protected Task currentTask;
	protected String currentTaskDate;
	protected EditText searchView;
	protected int activeTabId;
	public static final String sAusbildungsnachweis = " Ausbildungsnachweis Nr. ";
	public static final byte NOT_WEEK_INDEX = -1;
	public static final int NO_TASK_ID = 0;
	protected SearchWeekTaskAdapter searchAdapter;
	protected boolean isEdit;
	protected int currentDayOfWeek;
	private TimerChangeReceiver receiver;
	private final IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
	protected TaskInterface taskInterface;
	protected BerichtApplication application;
	protected Serializer serializer = new Persister();

	public void onCreate(Bundle bundle) {

		super.onCreate(bundle);
		calendar = Calendar.getInstance();
		dateFormat = new SimpleDateFormat(dateFormatPattern);
		application = (BerichtApplication) getApplication();
		
		user = WorkServer.getInstance().getUser();
		if (!application.isOffLineWork()){
			taskInterface = new OnlineTaskFactory();
			server = WorkServer.getInstance();
//			parser = new TaskXmlParser();
			serializer = new Persister();
		} else {
			taskInterface = new OfflineTaskFactory();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.i(TAG, "onResume()");
		if (WorkServer.getInstance().getWeeks() != null){
			weeks = WorkServer.getInstance().getWeeks();
			int index = currentWeekIndex > 0 ? currentWeekIndex: weeks.getWeekIndexByDate(Calendar.getInstance().getTimeInMillis() / 1000L);
//			int index = currentWeekIndex >= 0 ? currentWeekIndex: 6;
			if (index != NO_WEEK_INDEX){
				setCurrentTaskOfWeek(weeks.getWeek(index));
			}
			
		}
		if (!isEdit && !application.isOffLineWork()){
			receiver = new TimerChangeReceiver();
			registerReceiver(receiver, filter);
		}
	}
	
	

	@Override
	protected void onPause() {
		Log.i(TAG, "onPause()");
		super.onPause();
		if (receiver != null){
			unregisterReceiver(receiver);
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch (id) {
		case SEARCH_DIALOG_ID:
			Intent intent = new Intent(this, SearchActivity.class);
			startActivityForResult(intent, SEARCH_RESULT_OK);
			break;
//			TextView searchTitle = (TextView) getLayoutInflater().inflate(
//					R.layout.search_title, null);
//			builder.setCustomTitle(searchTitle);
////			searchTitle.setText("Search result: " + weeks.getWeekCount());
//			searchTitle.setText("Berichtshefte im Archiv");
//			searchAdapter = new SearchWeekTaskAdapter(this,
//					R.layout.search_row, null);
//			builder.setAdapter(searchAdapter,
//					new DialogInterface.OnClickListener() {
//
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
////							setCurrentTaskOfWeek(weeks.getWeek(which + 1));
//							if (isEdit){
//								Intent resultIntent = new Intent();
//								resultIntent.putExtra(TagesberichtActivity.RESULT_WEEK_DATA, which);
//								AbstractHomeActivity.this.setResult(Activity.RESULT_OK, resultIntent);
//								finish();
//							}																
//							else
//								setCurrentTaskOfWeek(weeks.getReverseWeek(which));
//						}
//					});
//			break;
		case CHOICE_FIRST_WEEK_DIALOG_ID:			
			String[] weekNumbers = new String[weeks.getWeekCount()];
			int first = 1;
			for (int i = 0; i<weekNumbers.length; i++){
				weekNumbers[i] = String.valueOf(first);
				first++;
			}
			builder.setItems(weekNumbers, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					String date = user.getMondayWeek(which);					
					server.setupFirstWeek(user, date);
					user.setStartUp(date);
				}
			});
			builder.setTitle(R.string.messageFirstTask);
			break;
		case PDF_DIALOG_ID:
			final View v = getLayoutInflater().inflate(R.layout.dialog_pdf, null);
			builder.setView(v);
			builder.setTitle(R.string.pdfTitle);
			builder.setPositiveButton(R.string.sendButton,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							//TODO реализовать отправку отчета по мылу
							TextView mailView = (TextView)v.findViewById(R.id.dialogPdfEmail);
							TextView subjView = (TextView)v.findViewById(R.id.dialogPdfSubject);
							TextView bodyView = (TextView)v.findViewById(R.id.dialogPdfBody);
							String mail = mailView.getText().toString();
							String subj = subjView.getText().toString();
							String body = bodyView.getText().toString();
							Date date;
//								date = dateFormat.parse(currentWeek.getStartDate());
							calendar.setTimeInMillis(currentWeek.getStartDate() * 1000L);
							String week = String.valueOf(getWeekOfYear(calendar));
							String year = String.valueOf(calendar.get(Calendar.YEAR));
							AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>(){
								
								ProgressDialog dialog;
								boolean isCancel = false;
								
								@Override
								protected void onPreExecute (){
									dialog = new ProgressDialog(builder.create().getContext());
									dialog.setMessage(getString(R.string.pdfSending));						
									dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
										
										@Override
										public void onCancel(DialogInterface dialog) {
											isCancel = true;
										}
									});
									dialog.show();
									
								}

								@Override
								protected Object doInBackground(Object... params) {
									String[] parameters = (String[]) params[0];
									String mail =  parameters[0];
									String subj =  parameters[1];
									String body =  parameters[2];
									String week =  parameters[3];
									String year =  parameters[4];
									
//										return server.sendReport(week, year, mail, subj, body);
									return "";
								}
								
								@Override 
								protected void onPostExecute(Object result) {
							         if (dialog != null && dialog.isShowing()){
							        	 dialog.dismiss();
							         }
							        	 
							         if (!isCancel){
								         if (result instanceof String && !WorkServer.NOT_CONNECT .equals(result)){
								        	 	Toast.makeText(AbstractHomeActivity.this, R.string.pdfHasSended, Toast.LENGTH_LONG).show();
											} else{
												Toast.makeText(AbstractHomeActivity.this, R.string.NotConnect, Toast.LENGTH_LONG).show();
											}
							         }
							     }

								
							};
							String[] params = new String[5];
							params[0] = mail;
							params[1] = subj;
							params[2] = body;
							params[3] = week;
							params[4] = year;
							Object result = null;
							task.execute(params, null, result);
							
							
						}
					});
			builder.setNegativeButton(R.string.cancelButton,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

						}
					});
			break;

		}
		return builder.create();

	}
		

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case SEARCH_DIALOG_ID:
			if (searchAdapter != null) {
				searchAdapter.setData(weeks);
				searchAdapter.notifyDataSetChanged();
			}
			break;
		case PDF_DIALOG_ID:
			EditText mailView = (EditText) dialog.findViewById(R.id.dialogPdfEmail);
			EditText bodyView = (EditText) dialog.findViewById(R.id.dialogPdfBody);
			EditText subjectView = (EditText) dialog.findViewById(R.id.dialogPdfSubject);
			mailView.setText(null);
			bodyView.setText(null);
			subjectView.setText(null);
			break;
			
		}

	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
	
	@Override
	protected void onDestroy(){
		Log.i(TAG, "onDestroy()");
		super.onDestroy();
		Log.i(TAG,"onDestroy()");
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		Intent intent;
		switch (id) {
	    case R.id.itemShare:
	    case R.id.itemAdd:
	    	intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
	    	if (id == R.id.itemAdd){
	    		startActivityForResult(intent, ADD_RESULT_OK);
	    	} else {
	    		startActivityForResult(intent, SHARE_RESULT_OK);
	    	}
	    	break;
	    case R.id.itemSettings:
//	    	intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_profile).concat("?u="+user.getUserId()).concat("&s="+user.getSessionId())));
	    	int width = getWindowManager().getDefaultDisplay().getWidth();
	    	intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_profile).concat("?u="+user.getUserId()).concat("&ss="+user.getSessionId()).concat("&pw="+width)));
	    	Log.i(TAG, intent.getData().toString());
	    	startActivity(intent);
	    	break;
	    case R.id.itemPdf:
	    	showDialog(PDF_DIALOG_ID);
	    	break;
	    
	    }
	    return true;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	  if (resultCode == Activity.RESULT_OK && (requestCode == ADD_RESULT_OK || requestCode == SHARE_RESULT_OK)) {
		  Uri dataUri = data.getData();
		  Cursor cursor = getContentResolver().query(dataUri, new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME}, null, null, null);
		  cursor.moveToFirst();
		  int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
		  int idIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
		  String name = "";
		  String email = "";
		  String id = "";
		  if (nameIndex >= 0)
			  name = cursor.getString(nameIndex);
		  if (idIndex >= 0)
			  id = cursor.getString(idIndex);
		  cursor.close();
		  cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);
		  cursor.moveToFirst();
		  int mailIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
		  if (mailIndex >= 0){
			  try{
				  email = cursor.getString(mailIndex);
			  }catch (CursorIndexOutOfBoundsException e) {
			}
		  }
		  cursor.close();
		  String str;
		  CharSequence body = null;
		  if (requestCode == 1){
			  str = String.format(getResources().getString(R.string.emailBodyTellFriend), name, user.getUserName());
		  } else {
			  str = String.format(getResources().getString(R.string.emailBodyInviteAusbilder), user.getUserName());			  
		  }
		  body = Html.fromHtml(str);
		  Intent ii = new Intent(Intent.ACTION_SEND);
		  ii.setType("text/html");
		  ii.putExtra(Intent.EXTRA_EMAIL  , new String[]{email});
		  ii.putExtra(Intent.EXTRA_SUBJECT, "Dein Berichtsheft-App.de Team");
		  ii.putExtra(Intent.EXTRA_TEXT   , body);
		  try {
		      startActivity(Intent.createChooser(ii, "Send mail..."));
		  } catch (android.content.ActivityNotFoundException ex) {
		      Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
		  }

		  
	  } else  if (resultCode == Activity.RESULT_OK && (requestCode == SEARCH_RESULT_OK)) {
		  int which = data.getIntExtra(TagesberichtActivity.RESULT_WEEK_DATA, 0);
		  if (isEdit){
				Intent resultIntent = new Intent();
				resultIntent.putExtra(TagesberichtActivity.RESULT_WEEK_DATA, which);
				AbstractHomeActivity.this.setResult(Activity.RESULT_OK, resultIntent);
				finish();
			}																
			else{
//				setCurrentTaskOfWeek(weeks.getReverseWeek(which));
				currentWeekIndex = which;
			}
	  }
	}
	public static int getWeekOfYear(Calendar cal){
		return cal.get(Calendar.WEEK_OF_YEAR);
	}
	
	public static void saveWeeks(Context mContext, Weeks weeks){
		File outWeeks = new File(mContext.getFilesDir(),"weeks.ser");
		if (outWeeks.exists()){
			try {
				outWeeks.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		FileOutputStream fileOutputStream;
		try {
			fileOutputStream = new FileOutputStream(outWeeks);
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
			objectOutputStream.writeObject(weeks);
			objectOutputStream.flush();
			objectOutputStream.close();
			fileOutputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e){
			e.printStackTrace();
		}
	}
	
	public static Weeks getWeeks(Context mContext){
		Weeks weeks = null;
		File inWeeks = new File(mContext.getFilesDir(),"weeks.ser");
		if (inWeeks != null && inWeeks.exists()){
			FileInputStream fileInputStream;
			try {
				fileInputStream = new FileInputStream(inWeeks);
				ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
				weeks = (Weeks) inputStream.readObject();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (StreamCorruptedException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			
		}
		return weeks;
	}

	protected void setSearchViewText() {
		if (currentWeek != null) {
			int currentWeekOfYear = 1;
			calendar.setTimeInMillis(currentWeek.getStartDate() * 1000L);
			currentWeekOfYear = getWeekOfYear(calendar);
				
			String dateText = currentWeek.getLongStartDate() + " - "
					+ currentWeek.getLongEndDate();
			String ausbildText = sAusbildungsnachweis + (currentWeek.getIndex() - 1);
			String text = getString(R.string.actuelleText) + " " + currentWeekOfYear + "\n";
			int index = text.length();
			text = text.concat(dateText);
			int indexAusbild = text.length();
			text += ausbildText;
			SpannableString spanString = new SpannableString(text);
			spanString.setSpan(
					new ForegroundColorSpan(getResources().getColor(
							R.color.colorDarkOrange)), 0, index,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			spanString.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.searchTextSize)), 0, index,
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			spanString.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.searchTextSizeSmall)), index, text.length(),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			spanString.setSpan(new ForegroundColorSpan(Color.BLACK),
					indexAusbild, text.length(),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			searchView.setText(spanString);

		}
	}

	protected void getTasks() {

		if (user != null) {
			if (!isEdit){
				AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>(){
					
					ProgressBar progressBar;

					@Override
					protected void onPostExecute(Object result) {
						super.onPostExecute(result);
						if (weeks != null){
							int index = currentWeekIndex >= 0 ? currentWeekIndex: weeks.getWeekIndexByDate(Calendar.getInstance().getTimeInMillis() / 1000L);
							setCurrentTaskOfWeek(weeks.getWeek(index));
						}
						if (progressBar != null)
							progressBar.setVisibility(View.INVISIBLE);
						
					}

					@Override
					protected void onPreExecute() {
						super.onPreExecute();
						progressBar = (ProgressBar) AbstractHomeActivity.this.findViewById(R.id.progressBar1);
						progressBar.setVisibility(View.VISIBLE);
						
					}

					@Override
					protected Object doInBackground(Object... params) {
						String result = server.getTasks(user.getUserId(), 2012);
						// Log.i(TAG, result);
						if (!WorkServer.NOT_CONNECT.equals(result)) {
//							Weeks weeks = null;
							try {
								weeks = serializer.read(Weeks.class, result);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							WorkServer.getInstance().setWeeks(weeks);
							saveWeeks(AbstractHomeActivity.this, weeks);

						}
						return null;
					}
					
				};
				task.execute(null);
				} else {
					Toast.makeText(this, R.string.NotConnect, Toast.LENGTH_LONG).show();
				}
			}

	}

	public abstract void setCurrentTaskOfWeek(Week week);
	
	public void setCurrentDateForTask(){
		if (currentTask != null && currentWeek != null){
			if (User.COMPLETE_WEEK.equals(user.getCompleteTask())){
				currentTask.setdate(currentWeek.getStartDate());
				
			} else {				
				calendar.setTimeInMillis(currentWeek.getStartDate() * 1000L);
				calendar.set(Calendar.DAY_OF_WEEK, currentDayOfWeek);
				currentTask.setdate(calendar.getTimeInMillis() / 1000L);
			}
		}
	}


	protected void initLayout() {

		MyTouchListener listener = new MyTouchListener();
		TextView addButtonView = (TextView) findViewById(R.id.addTaskButtonView);
		if (addButtonView != null){
			addButtonView.setOnTouchListener(listener);
		}
		ImageView createTaskView = (ImageView)findViewById(R.id.createView);
		if (createTaskView != null){
			createTaskView.setOnTouchListener(listener);
		}

		ImageView searchImageView = (ImageView) findViewById(R.id.searchView);
		searchImageView.setOnTouchListener(listener);
		searchView = (EditText) findViewById(R.id.editSearchView);
		searchView.setOnTouchListener(listener);

	}

	protected void initTabIcon() {
		TextSwitcher ts = (TextSwitcher) findViewById(R.id.tatigkeitView);
		changeIconTab(ts);
		ts = (TextSwitcher) findViewById(R.id.berufsschuleView);
		changeIconTab(ts);
		ts = (TextSwitcher) findViewById(R.id.themenView);
		changeIconTab(ts);
	}

	protected void changeIconTab(TextSwitcher ts) {
		int tabId = ts.getId();
		String value = null;
		TextView tv;
		switch (tabId) {
		case R.id.tatigkeitView:
			value = currentTask != null ? currentTask.getTaskText() : null;
			break;
		case R.id.berufsschuleView:
			value = currentTask != null ? currentTask.getBerufssText() : null;
			break;
		case R.id.themenView:
			value = currentTask != null ? currentTask.getThemenText() : null;
			break;
		}

		if (value != null && value.length() > 0) {
			tv = (TextView) ts.getChildAt(0);
			tv.setCompoundDrawablesWithIntrinsicBounds(getResources()
					.getDrawable(R.drawable.icon_tab_check_active), null, null,
					null);
			tv = (TextView) ts.getChildAt(1);
			tv.setCompoundDrawablesWithIntrinsicBounds(getResources()
					.getDrawable(R.drawable.icon_tab_check_active), null, null,
					null);
		} else {
			tv = (TextView) ts.getChildAt(0);
			tv.setCompoundDrawablesWithIntrinsicBounds(getResources()
					.getDrawable(R.drawable.icon_tab_check_inactive), null,
					null, null);
			tv = (TextView) ts.getChildAt(1);
			tv.setCompoundDrawablesWithIntrinsicBounds(getResources()
					.getDrawable(R.drawable.icon_tab_check_inactive), null,
					null, null);
		}

	}
	
	protected void startEditActivity(int taskId, boolean isCreateEverywhere) {
		Intent intent = new Intent(this, WochenberichtActivity.class);
		byte index = (currentWeek != null) ? (byte)currentWeekIndex: NOT_WEEK_INDEX;
		intent.putExtra(TagesberichtActivity.CUR_WEEK_INTENT_DATA, index);
		intent.putExtra(TagesberichtActivity.CREATE_EVERYWHERE_INTENT_DATA, isCreateEverywhere);
		if (taskId > 0)
			intent.putExtra(TagesberichtActivity.CUR_TASK_INTENT_DATA, taskId);
		intent.putExtra(TagesberichtActivity.EDIT_INTENT, true);
		intent.putExtra(TagesberichtActivity.CUR_DAY_INTENT_DATA, currentDayOfWeek);
		startActivityForResult(intent, 1);
		
	}
	
	class MyTouchListener implements View.OnTouchListener{

		/* (non-Javadoc)
		 * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
		 */
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int id = v.getId();
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				switch (id) {
				case R.id.editSearchView:
				case R.id.searchView:
					if (weeks != null && currentWeek != null){
//						showDialog(SEARCH_DIALOG_ID);
						Intent intent = new Intent(AbstractHomeActivity.this, SearchActivity.class);
						startActivityForResult(intent, SEARCH_RESULT_OK);
					} else {
						Toast.makeText(AbstractHomeActivity.this, R.string.searchNoWeeks, Toast.LENGTH_LONG).show();
					}
					break;
				case R.id.addTaskButtonView:
					startEditActivity(NO_TASK_ID, false);
					break;
				case R.id.createView:
					startEditActivity(NO_TASK_ID, true);
					break;
				}
				return true;
			} else
				return false;
		}
		
	}
	
	class TimerChangeReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i(TAG, ">>>>>> Change time and get new data from server");
			getTasks();
		}
		
	}

}
